﻿using System.Collections.Generic;
using System.Text;
using System.Windows;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void CopyLeaf()
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.LeafPanel == false)
            {
                MessageBox.Show("请先选中一个叶面板！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Expressions.LeafPanel leaf = curEx as Expressions.LeafPanel;
            if (leaf.LeafType == Expressions.LeafPanel.LeafPanelType.Root)
            {
                MessageBox.Show("树的叶首面板不支持复制操作！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            //复制也需要递归。
            if (leaf.ParentExpression == null ||
                leaf.ParentExpression is Expressions.Tree == false)
            {
                MessageBox.Show("发生意外，这个叶面板不在某个树上或被挂接到了某个意外的公式中！"
                    , Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Expressions.Tree pTree = leaf.ParentExpression as Expressions.Tree;

            List<string> xmlTextList = new List<string>();

            //这个方法得到的结果是逆序的——leaf的OutXml排列在最后一个。
            Expressions.LeafPanel.GetOutXmls(leaf, xmlTextList);

            StringBuilder sBuilder = new StringBuilder();
            for (int i = xmlTextList.Count - 1; i >= 0; i--)
            {
                string s = xmlTextList[i];
                sBuilder.Append(s);
            }

            Clipboard.SetData(DataFormats.UnicodeText, "<TreeLeaves SourceTreeID=\"" + pTree.ExID + "\">"
                        + sBuilder.ToString() + "</TreeLeaves>");
        }
    }
}
